package com.qyhl.module_home.splash;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.style.ClickableSpan;
import android.text.style.TextAppearanceSpan;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;
import com.qyhl.module_home.R;
import com.qyhl.module_home.common.HomeUrl;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.CommonDialog;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.base.ComminApplication;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.PathConfigConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogBean;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import java.util.List;
import java.util.UUID;

import cn.bingoogolapple.bgabanner.BGABanner;

/**
 * Created by qyhl on 2017/9/29.
 * 引导页面
 */

@Route(path = ARouterPathConstant.SPLASH)
public class SplashActivity extends AppCompatActivity {
    private static final String TAG = SplashActivity.class.getSimpleName();

    private BGABanner mBackgroundBanner, mForegroundBanner;
    ImageView splashIndicatorOne, splashIndicatorTwo, splashIndicatorThree;

    private int versionCode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //不显示标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        getH5Data();
        //退至后台重新点击图标，不重启app
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        compareVersion();
        isSameDay();
        isSkip();
    }

    /**
     * 用户协议
     */
    private void isSkip() {
        boolean isStart = SpfManager.getInstance(this).getBoolean("Skip", false);
        boolean privacy = SpfManager.getInstance(this).getBoolean("privacy", true);
        if (isStart) {//直接启动
            if (privacy) { //需要显示隐私条款
                SpanUtils spanUtils = new SpanUtils(this);
                spanUtils.append("欢迎使用" + getResources().getString(R.string.app_name) + "App!\n")
                        .append("为确保能够更好地为您提供阅读新闻、发布评论等相关服务,以及使用相关功能实现与应用能够安全稳定的运行,我们会接入由第三方提供的软件开发包(SDK)实现相关功能。分别是:\n")
                        .append("1.高德地图:便于您使用定位功能;\n" +
                                "2.友盟分享:便于您使用分享功能;\n" +
                                "3.友盟和微信:实现第三方登录功能。\n" +
                                "4.Leancloud即时通讯:提供聊天室服务。\n" +
                                "5.阿里云推送:实现统计分析、推送功能;\n" +
                                "6.Alipay支付:便于您在应用内使用支付宝提现功能;\n" +
                                "7.百度统计分析sdk：为App提供统计分析服务及基础反作弊服务;\n" +
                                "您可通过阅读")
                        .append("《隐私条款》")
                        .setSpans(new TextAppearanceSpan(this, R.style.clause)).setClickSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", "隐私条款");
                        bundle.putString("url", CommonUtils.getInstance().getPrivacyUrl());
                        bundle.putString("id", "");
                        bundle.putBoolean("hasShare", false);
                        RouterManager.router(ARouterPathConstant.ADV, bundle);
                    }
                }).append("和").append("《用户使用协议》")
                        .setSpans(new TextAppearanceSpan(this, R.style.clause)).setClickSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        Bundle bundle = new Bundle();
                        bundle.putString("title", "用户协议");
                        bundle.putString("url", "http://vod.136.i2863.com/customerUse.html");
                        bundle.putString("id", "");
                        bundle.putBoolean("hasShare", false);
                        RouterManager.router(ARouterPathConstant.ADV, bundle);
                    }
                }).append("了解第三方SDK收集、使用、存储、分享个人信息的情况，以及对您个人隐私的保护措施。\n" +
                        "是否同意+" + getResources().getString(R.string.app_name) + "App为您启用上述SDK?\n" +
                        "如您同意,请点击“同意”开始接受我们的服务。如果您仅需要使用浏览新闻资讯、观看电视和收听广播、接收推送消息、点赞、分享、等基本服务，则不需要注册成为我们的会员及提供上述信息，我们需要获取您手机的SD卡数据读写权限，以存储APP配置信息，进行数据缓存，节省用户流量；还需要获取您手机的当前状态，以保证APP的媒体播放、推送、分享功能。");
                new OtherDialog.Builder(this)
                        .setContentView(R.layout.home_layout_privacy_dialog)
                        .setText(R.id.content, spanUtils.create())
                        .setWidth(0.8f)
                        .setCancelable(false)
                        .setCanceledOnTouchOutside(false)
                        .setPrivacyOnClickListener(R.id.agree_btn, R.id.check_box, new OtherDialog.CheckListener() {
                            @Override
                            public void check(boolean isChecked, Dialog dialog) {
                                if (isChecked) {
                                    dialog.dismiss();
                                    SpfManager.getInstance(SplashActivity.this).putBoolean("privacy", false);

                                    Hawk.deleteAll();
                                    //创建唯一标识
                                    String uuId = UUID.randomUUID().toString();
                                    ActionLogUtils.deviceId = uuId;
                                    SpfManager.getInstance(SplashActivity.this).putString("DEVICE_ID", uuId);
                                    SpfManager.getInstance(SplashActivity.this).putBoolean("Skip", true);
                                    initView();
                                    setListener();
                                    processLogic();
                                    ActionLogUtils.getInstance().onEvent(ActionConstant.FIRSTSTART);
                                    //上传用户行为数据
                                    uploadLogAction();
                                    StatService.start(SplashActivity.this);
                                    ComminApplication.getApp().registerPush(getApplication());
                                    UMConfigure.init(SplashActivity.this, CommonUtils.getInstance().getUMAppKey(), CommonUtils.getInstance().getUMChannelId(), UMConfigure.DEVICE_TYPE_PHONE, "");
                                } else {
                                    Toast.makeText(getApplication(), "请认真阅读并同意以上协议内容！", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .setOnClickListener(R.id.refuse_btn, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                SpfManager.getInstance(SplashActivity.this).putBoolean("Skip", false);
                                SpfManager.getInstance(SplashActivity.this).putBoolean("privacy", true);
                                finish();
                            }
                        }).show();
            } else {//不需要
                uploadLogAction();
                StatService.start(SplashActivity.this);
                String deviceId = SpfManager.getInstance(this).getString("DEVICE_ID", "");
                if (StringUtils.isEmpty(deviceId)) {
                    //如未创建则创建
                    deviceId = UUID.randomUUID().toString();
                    SpfManager.getInstance(this).putString("DEVICE_ID", deviceId);
                }
                ActionLogUtils.deviceId = deviceId;
                RouterManager.router(ARouterPathConstant.MAIN);
                ActionLogUtils.getInstance().onEvent(ActionConstant.STARTUP);
                finish();
            }
        } else {//第一次启动
            SpfManager.getInstance(this).putBoolean("privacy", false);
            SpanUtils spanUtils = new SpanUtils(this);
            spanUtils.append("欢迎使用" + getResources().getString(R.string.app_name) + "App!\n")
                    .append("为确保能够更好地为您提供阅读新闻、发布评论等相关服务,以及使用相关功能实现与应用能够安全稳定的运行,我们会接入由第三方提供的软件开发包(SDK)实现相关功能。分别是:\n")
                    .append("1.高德地图:便于您使用定位功能;\n" +
                            "2.友盟分享:便于您使用分享功能;\n" +
                            "3.友盟和微信:实现第三方登录功能。\n" +
                            "4.Leancloud即时通讯:提供聊天室服务。\n" +
                            "5.阿里云推送:实现统计分析、推送功能;\n" +
                            "6.Alipay支付:便于您在应用内使用支付宝提现功能;\n" +
                            "7.百度统计分析sdk：为App提供统计分析服务及基础反作弊服务;\n" +
                            "您可通过阅读")
                    .append("《隐私条款》")
                    .setSpans(new TextAppearanceSpan(this, R.style.clause)).setClickSpan(new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    Bundle bundle = new Bundle();
                    bundle.putString("title", "隐私条款");
                    bundle.putString("url", CommonUtils.getInstance().getPrivacyUrl());
                    bundle.putString("id", "");
                    bundle.putBoolean("hasShare", false);
                    RouterManager.router(ARouterPathConstant.ADV, bundle);
                }
            }).append("和").append("《用户使用协议》")
                    .setSpans(new TextAppearanceSpan(this, R.style.clause)).setClickSpan(new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    Bundle bundle = new Bundle();
                    bundle.putString("title", "用户协议");
                    bundle.putString("url", "http://vod.136.i2863.com/customerUse.html");
                    bundle.putString("id", "");
                    bundle.putBoolean("hasShare", false);
                    RouterManager.router(ARouterPathConstant.ADV, bundle);
                }
            }).append("了解第三方SDK收集、使用、存储、分享个人信息的情况，以及对您个人隐私的保护措施。\n" +
                    "是否同意" + getResources().getString(R.string.app_name) + "App为您启用上述SDK?\n" +
                    "如您同意,请点击“同意”开始接受我们的服务。如果您仅需要使用浏览新闻资讯、观看电视和收听广播、接收推送消息、点赞、分享、等基本服务，则不需要注册成为我们的会员及提供上述信息，我们需要获取您手机的SD卡数据读写权限，以存储APP配置信息，进行数据缓存，节省用户流量；还需要获取您手机的当前状态，以保证APP的媒体播放、推送、分享功能。");
            new OtherDialog.Builder(this)
                    .setContentView(R.layout.home_layout_privacy_dialog)
                    .setText(R.id.content, spanUtils.create())
                    .setWidth(0.8f)
                    .setCancelable(false)
                    .setCanceledOnTouchOutside(false)
                    .setPrivacyOnClickListener(R.id.agree_btn, R.id.check_box, new OtherDialog.CheckListener() {
                        @Override
                        public void check(boolean isChecked, Dialog dialog) {
                            if (isChecked) {
                                dialog.dismiss();
                                SpfManager.getInstance(SplashActivity.this).putBoolean("privacy", false);
                                Hawk.deleteAll();
                                //创建唯一标识
                                String uuId = UUID.randomUUID().toString();
                                ActionLogUtils.deviceId = uuId;
                                SpfManager.getInstance(SplashActivity.this).putString("DEVICE_ID", uuId);
                                SpfManager.getInstance(SplashActivity.this).putBoolean("Skip", true);
                                initView();
                                setListener();
                                processLogic();
                                ActionLogUtils.getInstance().onEvent(ActionConstant.FIRSTSTART);
                                //上传用户行为数据
                                uploadLogAction();
                                StatService.start(SplashActivity.this);
                                ComminApplication.getApp().registerPush(getApplication());
                                UMConfigure.init(SplashActivity.this, CommonUtils.getInstance().getUMAppKey(), CommonUtils.getInstance().getUMChannelId(), UMConfigure.DEVICE_TYPE_PHONE, "");
                            }else{
                                Toast.makeText(getApplication(), "请认真阅读并同意以上协议内容！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    })
                    .setOnClickListener(R.id.refuse_btn, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SpfManager.getInstance(SplashActivity.this).putBoolean("Skip", false);
                            SpfManager.getInstance(SplashActivity.this).putBoolean("privacy", true);
                            finish();
                        }
                    }).show();
        }
    }

    /**
     * 判断是否是同一天打开app
     */
    private void isSameDay() {
        long curTime = System.currentTimeMillis();
        long saveTime = SpfManager.getInstance(this).getLong("time", 0);

        if (DateUtils.isSameDay(saveTime, curTime)) {
            SpfManager.getInstance(this).putBoolean("isFirst", false);
        } else {
            SpfManager.getInstance(this).putBoolean("isFirst", true);
        }
        SpfManager.getInstance(this).putLong("time", curTime);
    }

    /**
     * 获取H5页面传递的数据
     */
    private void getH5Data() {
        Intent intent = getIntent();
        Uri uri = intent.getData();
        if (uri != null) {
            String pId = uri.getQueryParameter("pId");
            String pType = uri.getQueryParameter("pType");
            PathConfigConstant.H5_PID = pId;
            PathConfigConstant.H5_PTYPE = pType;
        }
    }

    /**
     * 比较版本，是否覆盖安装
     */
    private void compareVersion() {
        int code = SpfManager.getInstance(this).getInt("app_code", -1);
        try {
            PackageManager manager = getPackageManager();
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (code != versionCode) {
            SpfManager.getInstance(this).putInt("app_code", versionCode);
            Hawk.deleteAll();
        }

    }


    /**
     * 上传用户行为数据
     */
    private void uploadLogAction() {
        List<ActionLogBean> actions = ActionLogUtils.getInstance().getActionData();
        //清除用户数据
        ActionLogUtils.getInstance().clearData();
        if (actions != null && actions.size() != 0) {
            EasyHttp.post(HomeUrl.USER_ACTION_DATA_URL)
                    .upString(new Gson().toJson(actions))
                    .execute(new SimpleCallBack<String>() {
                        @Override
                        public void onError(ApiException e) {

                        }

                        @Override
                        public void onSuccess(String s) {

                        }
                    });

        }


    }


    /**
     * 初始化控件
     */
    private void initView() {
        setContentView(R.layout.home_activity_splash);
        mBackgroundBanner = (BGABanner) findViewById(R.id.banner_guide_background);
        mForegroundBanner = (BGABanner) findViewById(R.id.banner_guide_foreground);
        splashIndicatorOne = (ImageView) findViewById(R.id.splash_indicator_one);
        splashIndicatorTwo = (ImageView) findViewById(R.id.splash_indicator_two);
        splashIndicatorThree = (ImageView) findViewById(R.id.splash_indicator_three);

    }

    /**
     * 设置进入按钮和跳过按钮控件资源 id 及其点击事件
     * 如果进入按钮和跳过按钮有一个不存在的话就传 0
     * 在 BGABanner 里已经帮开发者处理了防止重复点击事件
     * 在 BGABanner 里已经帮开发者处理了「跳过按钮」和「进入按钮」的显示与隐藏
     */
    private void setListener() {
        mBackgroundBanner.setEnterSkipViewIdAndDelegate(R.id.btn_guide_enter, 0, new BGABanner.GuideDelegate() {
            @Override
            public void onClickEnterOrSkip() {
                new CommonDialog.Builder(SplashActivity.this)
                        .setTitle("权限申请", R.color.global_black_lv1)
                        .setMessage("存储空间权限，用于您保存图片、上传图片或视频等", R.color.global_black_lv2)
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                MPermissionUtils.requestPermissionsResult(SplashActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_SETTINGS, Manifest.permission.WRITE_SETTINGS}, new MPermissionUtils.OnPermissionListener() {
                                    @Override
                                    public void onPermissionGranted() {
                                        RouterManager.router(ARouterPathConstant.MAIN);
                                        finish();
                                    }

                                    @Override
                                    public void onPermissionDenied() {
                                        RouterManager.router(ARouterPathConstant.MAIN);
                                        finish();
                                    }
                                });
                            }
                        }, R.color.global_base)
                        .setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                RouterManager.router(ARouterPathConstant.MAIN);
                                finish();
                            }
                        }, R.color.global_gray_lv2).show();
            }
        });

        mBackgroundBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                reSet();
                switch (position) {
                    case 0:
                        splashIndicatorOne.setBackgroundResource(R.drawable.home_splash_indicator_checked);
                        break;
                    case 1:
                        splashIndicatorTwo.setBackgroundResource(R.drawable.home_splash_indicator_checked);
                        break;
                    case 2:
                        splashIndicatorThree.setBackgroundResource(R.drawable.home_splash_indicator_checked);
                        break;
                    default:
                        break;
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            RouterManager.router(ARouterPathConstant.MAIN);
            finish();
        }
    }

    /**
     * 设置数据源
     */
    private void processLogic() {
        mBackgroundBanner.setData(R.drawable.splash_bg0, R.drawable.splash_bg1, R.drawable.splash_bg2);
        mForegroundBanner.setData(R.drawable.splash_fg0, R.drawable.splash_fg1, R.drawable.splash_fg2);
    }

    /**
     * 重置指示器
     */
    private void reSet() {
        splashIndicatorOne.setBackgroundResource(R.drawable.home_splash_indicator_unchecked);
        splashIndicatorTwo.setBackgroundResource(R.drawable.home_splash_indicator_unchecked);
        splashIndicatorThree.setBackgroundResource(R.drawable.home_splash_indicator_unchecked);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("引导页");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("引导页");
        MobclickAgent.onPause(this);
    }


}
